// 工人服务
const { v4 } = require('uuid');
const DbService = require('./db2');
const BaseService = require('./base');
const { TABLE_NAME } = require('../models');
const { logger } = require('../utils');


class WorkerService extends BaseService {
  constructor() {
    super();
    this.dbService = new DbService(TABLE_NAME.worker);
  }

  async create(data) {
    const record = {
      ...data,
      id: v4(), // 生成唯一id
      createdOn: new Date(),
      status: '',
    };

    if (this.dbService) {
      await this.dbService.insert(record);
    }
    return record;
  }

  async delete(workerId) {
    try {
      const target = await this.dbService.getById(workerId);
      Object.assign(target, { status: 'QUIT_JOB', deletedOn: new Date() });
      await this.dbService.updateById(workerId, target);
      return 0;
    } catch (error) {
      logger.error({
        action: 'worker/delete',
        data: workerId,
        errMessage: error.message,
      });
      return -1;
    }
  }
  async clean(id) {
    try {
      await this.dbService.deleteById(id);
      return 0;
    } catch (error) {
      logger.error({
        action: 'worker/clean',
        data: id,
        errMessage: error.message,
      });
      return -1;
    }
  }

  async batchUpdate(list) {
    try {
      return Promise.all(
        list.map(item =>
          this.dbService.updateById(item.id, item),
        ),
      );
    } catch (error) {
      logger.error({
        action: 'worker/batchUpdate',
        data: list,
        errMessage: error.message,
      });
      return false;
    }
  }

  async searchCount({ where, name, mobile }) {
    let result = this.dbService.knex(TABLE_NAME.worker)
      .where(where || {});
    if (name) {
      result = result.whereILike('name', `%${name}%`);
    }
    if (mobile) {
      result = result.andWhereLike('mobile', `%${mobile}%`);
    }
    const [{ count }] = await result.count({ count: '*' });
    return count;
  }

  async search({ where, name, mobile, offset, limit }) {
    let result = this.dbService.knex(TABLE_NAME.worker).select()
      .where(where || {});
    if (name) {
      result = result.whereILike('name', `%${name}%`);
    }
    if (mobile) {
      result = result.andWhereLike('mobile', `%${mobile}%`);
    }
    return result.limit(limit).offset(offset);
  }
}

module.exports = WorkerService;
